<template>
  <ClDialog v-bind="$attrs" :title="getTitle" width="750px">
    <ClForm ref="formRef" label-width="100px" :form-item="formItem" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('atClose')">取消</el-button>
        <el-button type="primary" @click="onSure">确定</el-button>
      </span>
    </template>
  </ClDialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useProjectInfoStore } from '@/store/projectInfo'
import { projectInfoList } from '@/api/project-info'
const { setProjectInfo, projectInfo } = useProjectInfoStore()
onMounted(() => {
  init()
})
const loaded = ref(false)
const projectList = ref<any[]>([])
const formItem = ref([
  {
    key: 'projectName',
    value: '',
    name: '项目名称',
    formType: 'select',
    verificationData: '必填',
    elementConfig: {
      textareaWidth: '600px',
      options: []
    }
  }
])
const init = async () => {
  try {
    loaded.value = false
    const { rows }: any = await projectInfoList({})
    projectList.value = cloneDeep(rows)
    formItem.value[0].elementConfig.options = rows.map((item: any) => ({
      key: item.id,
      value: item.projectName
    }))
    formItem.value[0].value = projectInfo.id
    loaded.value = true
  } catch (error) {
    console.log(error)
    loaded.value = true
  }
}

const formRef = ref<any>()
const onSure = async () => {
  const cb = async (res) => {
    // 获取项目信息
    const project = projectList.value.find((item) => item.id === res.projectName)

    if (!project) {
      ElMessage.error('项目不存在')
      return
    }
    // 持久化存储项目信息
    await setProjectInfo(project)
    // emit('atClose')
    window.location.reload()
  }
  await formRef.value.onsubmit(cb)
}
onMounted(() => {})
const getTitle = computed(() => {
  return props.type
})

interface infoType {
  [props: string]: any
}
const props = defineProps<{ info: infoType; type: string }>()

const emit = defineEmits<{
  (e: 'atClose', str?: string | undefined): void
}>()
</script>

<style scoped lang="scss"></style>
